import React, { Component } from 'react';
// import PropTypes from 'prop-types';
import MarkdownIt from 'markdown-it';
import hljs from 'utils/hl.js';
import { Balloon, Input, Select } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import MdEditor from 'components/mdEditor';
import List from '@txdfe/at-list';
import YundouName from 'components/yundouName';
import LogItem from './logItem';
import { PROJECT_WRITE_ROLES } from 'utils/constants.js';
import { access } from 'components/accessContainer/util';
import utils from 'utils/index';
import { getFeature } from 'utils/features';
import TextAvatar from '@txdfe/at-text-avatar';
import './index.scss';
import { filterXSS } from 'xss';
import { ENUM } from 'utils/constants';
import track from 'utils/track';
import intl from '../../../../../../../../../locale';

const { pathResource } = window.FORCE;
const md = new MarkdownIt({
  html: true,
  linkify: true,
  breaks: true,
  typographer: true,
  highlight(str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(lang, str).value;
      } catch (__) {
        return '';
      }
    }

    return ''; // 使用额外的默认转义
  },
});

const { ctrlTxt } = ENUM.getOSKeyMap();

const prefix = 'mr-logs';
export default class Logs extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isEditing: false,
      isMoreData: false,
      // 操作类型
      logType: 'all',
      isEditorShow: false,
    };
  }

  onCancelEditing = () => {
    this.setState({
      isEditing: false,
    });
  };

  onDescClick = () => {
    this.setState({
      isEditing: true,
    });
  };

  onMDSubmit = (value) => {
    const modifyData = {};
    modifyData.description = value;
    this.props.modifyCr(modifyData);
    this.onCancelEditing();
  };

  // 描述
  renderDesc = () => {
    const { codeReviewDetail } = this.props;
    const { description } = codeReviewDetail;
    const { role } = pathResource;
    const { isEditing } = this.state;
    const hasEditAccess = access(PROJECT_WRITE_ROLES, role);

    if (isEditing) {
      return (
        <MdEditor
          placeholder={intl.get({
            id: 'code-assets.components.logs.EnterADescription',
            defaultMessage: '请输入描述',
          })}
          initValue={codeReviewDetail.description}
          onSubmit={(value) => this.onMDSubmit(value)}
          onCancel={this.onCancelEditing}
        />
      );
    } else if (!description) {
      // 没有描述时：有权限修改
      if (hasEditAccess) {
        return (
          <Input
            style={{ width: '100%' }}
            onClick={this.onDescClick}
            placeholder={intl.get({
              id: 'code-assets.components.logs.AddDescription',
              defaultMessage: '添加描述...',
            })}
          />
        );
      } else {
        // 无权限修改
        return (
          <div className="desc-placeholder">
            {intl.get({
              id: 'code-assets.components.logs.TheInitiatorWasVeryBusy',
              defaultMessage: '发起人很忙，没有留下任何信息',
            })}
          </div>
        );
      }
    } else if (hasEditAccess) {
      // 有描述、有权限
      return (
        <Balloon.Tooltip
          trigger={
            <div
              className={'markdown-body'}
              onClick={this.onDescClick}
              // eslint-disable-next-line react/no-danger
              dangerouslySetInnerHTML={{
                __html: filterXSS(md.render(description || ''), {
                  onIgnoreTagAttr: (_, name, value) => {
                    return `${name}=${value}`;
                  },
                }),
              }}
            />
          }
          align="t"
          triggerType="hover"
        >
          {intl.get({
            id: 'code-assets.components.logs.ClickToEdit',
            defaultMessage: '点击即可编辑',
          })}
        </Balloon.Tooltip>
      );
    } else {
      // 有描述无权限
      return (
        <div
          className="markdown-body"
          // eslint-disable-next-line react/no-danger
          dangerouslySetInnerHTML={{
            __html: filterXSS(md.render(description || ''), {
              onIgnoreTagAttr: (_, name, value) => {
                return `${name}=${value}`;
              },
            }),
          }}
        />
      );
    }
  };

  showAllCommentArea = () => {
    const { changesReducer, mrCommentConfig } = this.props;
    const { allComments = [] } = changesReducer;
    const hasPermission =
      pathResource.isArchive === 'false' &&
      utils.allowComments(allComments.length, mrCommentConfig);
    if (!hasPermission) {
      return;
    }
    this.setState({
      isEditorShow: true,
    });
  };

  getCurSummaryLogs = () => {
    const { summaryLogs } = this.props;
    if (!summaryLogs) {
      return [];
    }
    const { logType } = this.state;
    return summaryLogs.filter((item) => {
      if (logType === 'action') {
        return item.avatarType !== 'AUTHOR';
      }
      return true;
    });
  };

  onSubmitWhole = (value, is_draft, parent_note_id) => {
    const { codeReviewDetail } = this.props;
    this.props.postInlineComments(
      {
        note: value,
        parent_note_id: parent_note_id || '',
        is_draft: !!is_draft,
      },

      () => {
        this.setState({
          isEditorShow: false,
        });
      },
    );

    track({
      action: 'post_overall_comment',
      page: 'Repo-MR',
      type: '',
      mr_id: codeReviewDetail.id,
    });
  };

  // noDraft 是否有保存草稿按钮
  renderMd = (noDraft = false) => {
    return (
      <MdEditor
        onSubmitImmediate={this.onSubmitWhole}
        onCancel={() => {
          this.setState({
            isEditorShow: false,
          });
        }}
        placeholder={intl.get({
          id: 'code-assets.components.logs.EnterAComment',
          defaultMessage: '请输入评论',
        })}
        help={
          noDraft
            ? intl.get(
                {
                  id: 'code-assets.components.logs.CtrltxtShiftEnterPublishDirectly',
                  defaultMessage: '{ctrlTxt} + Shift + Enter 直接发布',
                },
                { ctrlTxt },
              )
            : intl.get(
                {
                  id: 'code-assets.components.logs.CtrltxtEnterSaveDraftCtrltxt',
                  defaultMessage: '{ctrlTxt} + Enter 存草稿，{ctrlTxt} + Shift + Enter 直接发布',
                },
                { ctrlTxt },
              )
        }
        submitBtnText={
          noDraft
            ? ''
            : intl.get({
                id: 'code-assets.components.logs.SaveAsDraft',
                defaultMessage: '保存为草稿',
              })
        }
        initValue={''}
      />
    );
  };

  render() {
    const { codeReviewDetail, changesReducer, mrCommentConfig } = this.props;
    const { allComments = [] } = changesReducer;
    const { author, created_at, is_auto_create } = codeReviewDetail;
    const { logType } = this.state;

    const { role } = pathResource;
    const hasEditAccess = access(PROJECT_WRITE_ROLES, role);
    const hasPermission =
      pathResource.isArchive === 'false' &&
      utils.allowComments(allComments.length, mrCommentConfig);

    // summaryLogs存在每条记录不止一个动态,比如批量提交草稿，处理成多条数据
    const curSummaryLogs = this.getCurSummaryLogs();
    const logTotal = curSummaryLogs.length;
    const { user } = window.FORCE;
    const logTotal_5 = logTotal - 5;
    return (
      <div className={`${prefix}`}>
        <div className={`${prefix}-title`}>
          <div className={`${prefix}-title-left`}>
            {intl.get({ id: 'code-assets.components.logs.LatestNews', defaultMessage: '最新动态' })}
          </div>
          <div className={`${prefix}-title-right`}>
            <Select
              value={logType}
              onChange={(value) => {
                this.setState({
                  logType: value,
                });

                track({
                  action: 'mr_activity_filter',
                  page: 'Repo-MR',
                  type: '',
                  mr_id: codeReviewDetail.id,
                  filter: value === 'all' ? 'all' : 'operation_history',
                });
              }}
              style={{ width: 110, minWidth: 'auto' }}
              hasBorder={false}
              popupProps={{
                align: 'tr br',
              }}
            >
              <Select.Option value="all">
                {intl.get({
                  id: 'code-assets.components.logs.AllDynamic',
                  defaultMessage: '全部动态',
                })}
              </Select.Option>
              <Select.Option value="action">
                {intl.get({
                  id: 'code-assets.components.logs.OperationHistory',
                  defaultMessage: '操作历史',
                })}
              </Select.Option>
            </Select>
          </div>
        </div>
        <div className={`${prefix}-content`}>
          {/* 描述 */}
          <div className={`${prefix}-content-desc`}>
            <div className={`${prefix}-content-desc-left`}>
              <YunxiaoIcon type="message-group-line" className="mr-log-chat-icon" />
              <span className="log-line" />
            </div>
            <div className={`${prefix}-content-desc-right`}>
              <div className="title">
                <div className="title-left">
                  {is_auto_create === true || is_auto_create === 'true' ? (
                    <YundouName hasAvatar />
                  ) : (
                    <Balloon.Tooltip
                      align="t"
                      trigger={
                        <TextAvatar
                          image={author.avatar_url}
                          text={author.name}
                          needAddedText
                          size="xs"
                        />
                      }
                      text={author.name}
                    />
                  )}
                  &nbsp;
                  <span>
                    {getFeature('project.mr.info.default.text').create}
                  </span>
                  {/* {
                     description && */}
                  <span>
                    {intl.get({
                      id: 'code-assets.components.logs.TheDescriptionIsAsFollows',
                      defaultMessage: '，描述如下：',
                    })}
                  </span>
                  {/* } */}
                </div>
                <div className="title-right">{utils.getBeautyTime(created_at)}</div>
              </div>
              {/* TODO: 暂不支持获取最新修改人，编辑描述，继续保持原有功能，在原有位置 */}
              <div
                className={`${this.state.isEditing ? 'isEditing' : ''} ${
                  hasEditAccess ? '' : 'disabled'
                } ${codeReviewDetail.description ? '' : 'no-description'} mr-des-content`}
              >
                {this.renderDesc()}
              </div>
            </div>
          </div>
          {logTotal > 5 ? (
            <div
              className="log-item more"
              onClick={() => {
                const { isMoreData } = this.state;
                this.setState({
                  isMoreData: !isMoreData,
                });
              }}
            >
              <div className="log-item-left  no-mt">
                <div className="log-item-icon">
                  <YunxiaoIcon type="more-line" />
                  <div className="log-line" />
                </div>
              </div>
              <div className="log-item-right">
                <div className="log-item-title has-pb">
                  {this.state.isMoreData
                    ? intl.get({
                        id: 'code-assets.components.logs.HideEarlierDynamics',
                        defaultMessage: '隐藏较早的动态',
                      })
                    : intl.get(
                        {
                          id: 'code-assets.components.logs.DisplaysEarlierLogtotalDynamicRecords',
                          defaultMessage: '显示较早的 {logTotal} 条动态',
                        },
                        { logTotal: logTotal_5 },
                      )}
                </div>
              </div>
            </div>
          ) : null}
          <div>
            {this.state.isMoreData ? (
              <List
                pagination={{
                  onLoadMore: (page) => {
                    this.props.getSummaryLogs(page);
                  },
                  hasMore: false,
                  useWindow: false,
                  getScrollParent: () => {
                    return document.querySelector('#container');
                  },
                }}
              >
                {curSummaryLogs.map((log) => (
                  <LogItem log={log} {...this.props} />
                ))}
              </List>
            ) : (
              <div>
                {curSummaryLogs.slice(-5).map((log) => (
                  <LogItem log={log} {...this.props} />
                ))}
              </div>
            )}
          </div>
          <div className="comment-input-md total-comment">
            <div>
              <TextAvatar
                image={user.avatar}
                text={user.nickname}
                // needAddedText
                size="small"
              />
            </div>
            <div className="input-area">
              {this.state.isEditorShow ? (
                this.renderMd(true)
              ) : (
                <div className="placeholder-text">
                  <Input
                    placeholder={intl.get({
                      id: 'code-assets.components.logs.LetSTalkAboutYour',
                      defaultMessage: '展开讲讲你的看法',
                    })}
                    onClick={() => {
                      this.setState({
                        isEditorShow: true,
                      });
                    }}
                    disabled={!hasPermission}
                    style={{ width: '100%' }}
                  />
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  }
}
